import { NextRequest, NextResponse } from 'next/server'
import { projectQueries, createAuditLog } from '@/lib/database-prisma'
import { getUserFromRequest } from '@/lib/auth-utils'

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const userInfo = await getUserFromRequest(request)
    if (!userInfo) {
      return NextResponse.json({ error: '未授权' }, { status: 401 })
    }

    const { projectId } = await params
    const projectIdNum = parseInt(projectId)
    if (isNaN(projectIdNum)) {
      return NextResponse.json({ error: '无效的项目ID' }, { status: 400 })
    }

    const body = await request.json()
    const { isArchived } = body

    if (typeof isArchived !== 'boolean') {
      return NextResponse.json({ error: 'isArchived必须是布尔值' }, { status: 400 })
    }

    // 检查项目是否存在
    const project = await projectQueries.findById.get(projectIdNum)
    if (!project) {
      return NextResponse.json({ error: '项目不存在' }, { status: 404 })
    }

    // 更新项目归档状态
    await projectQueries.updateArchiveStatus.run(isArchived, projectIdNum)

    // 记录审计日志
    await createAuditLog(userInfo.id, {
      type: 'project',
      action: isArchived ? 'archive' : 'unarchive',
      projectId: projectIdNum,
      projectName: project.name,
      time: new Date().toISOString()
    }, projectIdNum)

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('更新项目归档状态失败:', error)
    return NextResponse.json({ error: '更新项目归档状态失败' }, { status: 500 })
  }
} 